﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Runtime.Serialization;
using System.IO;
using MovieRental.XmlDataProviderCore.Exceptions;

namespace MovieRental.XmlDataProviderCore
{
    internal class XmlEntityConverter
    {
        private MemoryStream _tempStream;

        internal object ConvertFromXElement(XElement xml, Type objectType)
        {
            var serializer = new DataContractSerializer(objectType);
            object result;
            try
            {
                _tempStream = new MemoryStream();
                xml.Save(_tempStream);
                _tempStream.Seek(0, SeekOrigin.Begin);
                result = serializer.ReadObject(_tempStream);
                _tempStream.Close();
            }
            catch (Exception ex)
            {
                throw new EntityConversionException("Can't convert xml into entity.", ex);
            }
            return result;
        }

        internal XElement ConvertToXElement(object obj)
        {
            var serializer = new DataContractSerializer(obj.GetType());
            XElement result;
            try
            {
                _tempStream = new MemoryStream();
                serializer.WriteObject(_tempStream, obj);
                _tempStream.Seek(0, SeekOrigin.Begin);
                result = XElement.Load(_tempStream);
                _tempStream.Close();
            }
            catch (Exception ex)
            {
                throw new EntityConversionException("Can't convert xml into entity.", ex);
            }
            return result;
        }
    }
}
